package com.hkts.management.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class AddressUtils {

    public static String getLonLat(String address){
        String startArea = StringUtil.filtered(address);
        //返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=f05b5ff858819b9d9b90b8e534193e00&address="+startArea;
        String queryResult = getResponse(queryUrl);  //高德接品返回的是JSON格式的字符串
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONObject jobJSON = JSONObject.parseObject(job.get("geocodes").toString().substring(1, job.get("geocodes").toString().length()-1));
        if (jobJSON == null){
            return null;
        }
        return jobJSON.get("location").toString();
    }
    public static String getResponse(String serverUrl){
        //用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while((line = in.readLine()) != null){
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
    /**
     * 0.得到两个地址间距离
     * */
    public static BigDecimal getDistanceByAdress(String start,String end){
        String startLonLat = getLonLat(start);
        String endLonLat = getLonLat(end);
        long dis = getDistance(startLonLat,endLonLat);
        BigDecimal distances = getDistances(Long.toString(dis));
        return distances;
    }
    /**
     * 2.经纬度算出两点间距离
     * */
    public static long getDistance(String startLonLat, String endLonLat){


        //返回起始地startAddr与目的地endAddr之间的距离，单位：米
        Long result = new Long(0);
        String queryUrl = "http://restapi.amap.com/v3/distance?key=f05b5ff858819b9d9b90b8e534193e00&origins="+startLonLat+"&destination="+endLonLat +"&type=0";
        //String queryUrl = "http://restapi.amap.com/v4/direction/truck?key=f05b5ff858819b9d9b90b8e534193e00&origin="+startLonLat+"&destination="+endLonLat +"&size=3";
        String queryResult = getResponse(queryUrl);
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONArray ja = job.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        result = Long.parseLong(jobO.get("distance").toString());
        System.out.println("距离2："+result);
        return result;
    }
    public static BigDecimal getDistances(String str){
        BigDecimal num1 = new BigDecimal(str);
        BigDecimal num2 = new BigDecimal(1000);
        BigDecimal divide = num1.divide(num2, 1, RoundingMode.HALF_UP);
        return divide;
    }
    // 将经纬度getLng， getLat 通过getAmapByLngAndLat方法转换地址
    public static Result<Object> getAmapByLngAndLat(String getLng, String getLat) throws Exception {
        String url;
        try {
            url = "http://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + getLng + "," + getLat
                    + "&key=f05b5ff858819b9d9b90b8e534193e00&radius=0&extensions=base";
            String queryResult = getResponse(url); // 高德接品返回的是JSON格式的字符串
            if (queryResult == null) {
                return ResultUtil.error("-1") ;
            }
            // 将获取结果转为json 数据
            JSONObject obj = JSONObject.parseObject(queryResult);
            if (obj.get("status").toString().equals("1")) {
//              如果没有返回-1
                JSONObject regeocode = obj.getJSONObject("regeocode");
                return ResultUtil.data(regeocode);
//                if (regeocode.size() > 0) {
//                    // 在regeocode中拿到 formatted_address 具体位置
//                    String formatted = regeocode.get("formatted_address").toString();
//                    Object addressComponent = regeocode.get("addressComponent");
////                    Map<String,Object> resultMap = new HashMap<>();
////                    resultMap.put("result",addressComponent);
//                    return ResultUtil.data(addressComponent);
//
//                } else {
//                    System.out.println("未找到相匹配的地址！");
//                    return  ResultUtil.error("-1");
//
//                }
            } else {
                System.out.println("请求错误！");
                return  ResultUtil.error("-1");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return  ResultUtil.error("-1");
    }
    public static void main(String[] args) {
        /*getDistance("117.185862,39.094783","112.564306,37.742941");
        getDistance("121.508903,25.044319","114.514859,38.042306");

        BigDecimal num1 = new BigDecimal("1000");
        BigDecimal num2 = new BigDecimal("500");
        BigDecimal subtract = num1.subtract(num2);
        System.out.println(subtract);*/

        String lonLat = getLonLat("123");
        System.out.println(lonLat);
        BigDecimal distanceByAdress = getDistanceByAdress("北京北京市东城区地铁2号线内环安定门[地铁站]", "陕西省榆林市榆阳区金鸡滩镇陕西有色工业园区航来湾煤场");
        System.out.println(distanceByAdress);
    }
}
